<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="ImageUpload"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    // 上传之前的钩子函数 - 校验文件的大小 + 类型
    beforeAvatarUpload(file) {
      // console.log(file)
      //   jpg png gif bmp
      const fileType = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
      const isJPG = fileType.includes(file.type)
      //   限制上传图片的大小 必须小于 5MB
      // file.size === B / 1024= KB /1024 = MB
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt5M
    },
    ImageUpload(obj) {
      // 1. 初始化COS
      const cos = new COS({
        SecretId: 'AKIDoUwABxUmqfFn9JI7kCQPAh04whFZifp0',
        SecretKey: 'AGGH8nDOPDnHhz3wd9SXQ7cx68AA86Ku'
      })
      cos.putObject({
        Bucket: 'heimahr-1318554281', // 存储痛的名称
        Region: 'ap-shanghai', // 存储桶的地域
        Key: obj.filename + new Date(), // 文件名称
        StorageClass: 'STANDARD', // 上传模式 - 标准模式
        Body: obj.file // 文件对象
      }, (err, data) => {
        // err 错误对象
        // data 返回结果
        // console.log(data)
        if (data.statusCode === 200 && data.Location) {
          // 上传成功
          // 1. 派发事件 input
          // https:// + heimahr-1318554281.cos.ap-shanghai.myqcloud.com/fileSun%20Jun%2004%202023%2016%3A16%3A21%20GMT%2B0800%20%28%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4%29
          this.$message.success('上传图片成功')
          this.$emit('input', 'https://' + data.Location)
        } else {
          console.log(err)
          this.$message.error('上传图片失败')
        }
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
